package com.party.jackclientandroid.ui_mine;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.party.jackclientandroid.BaseActivityTitle;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.adapter.RecommendPresentAdapter;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.UserService;
import com.party.jackclientandroid.api.VipService;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.CommonResult;
import com.party.jackclientandroid.bean.RankingBean;
import com.party.jackclientandroid.controller.DialogController;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.utils.CommonUtil;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.zyyoona7.popup.EasyPopup;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.tencent.mm.opensdk.modelmsg.SendMessageToWX.Req.WXSceneSession;
import static com.tencent.mm.opensdk.modelmsg.SendMessageToWX.Req.WXSceneTimeline;

/**
 * 推荐有礼
 */
public class RecommendPresentActivity extends BaseActivityTitle {

    @BindView(R.id.invite_sum_reward_tv)
    TextView invite_sum_reward_tv;
    @BindView(R.id.charge_sum_reward_tv)
    TextView charge_sum_reward_tv;
    @BindView(R.id.partner_interest_tv)
    TextView partner_interest_tv;
    @BindView(R.id.qr_code_iv)
    ImageView qr_code_iv;
    @BindView(R.id.share_btn)
    Button share_btn;
    @BindView(R.id.whole_layout)
    LinearLayout whole_layout;
    @BindView(R.id.desc_tv)
    TextView desc_tv;
    @BindView(R.id.recommend_phone)
    TextView recommendPhone;
    @BindView(R.id.rv_recommend_present)
    RecyclerView rvRecommendPresent;

    private List<RankingBean> rankingBeanList;
    private UserService userService;
    private VipService vipService;
    private EasyPopup easyPopup;
    private String APP_ID = "wx3b6ef958f00135d3";
    private IWXAPI iwxapi;
    private String qr_code_image_url;
    private RecommendPresentAdapter adapter;
    private List<RankingBean> data;
    private Context context;


//    public Object getRankingData() {
//
//        addDisposableIoMain((Resl<List<rankingBeanList>> daf) -> {
//            List<rankingBeanList> dd = daf.getData();
//
//            if (dd.size() > 3) {
//
//                switch (i) {
//                    case 0:
//                        dd.get(0).set
//                        break;
//                    case 1:
//                        break;
//                }
//            }
//        });
//    }


    private enum SHARE_TYPE {Type_WXSceneSession, Type_WXSceneTimeline}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recommend_present);
        ButterKnife.bind(this);
        initData();
        RequestData();
    }

    protected void initData() {
        setMiddleText("推荐有礼");
        initPopup();
        context = getApplicationContext();
        data = new ArrayList<>();
        recommendPhone.setText(mApplication.getUser().getPhone());
        iwxapi = WXAPIFactory.createWXAPI(this, APP_ID, false);
        iwxapi.registerApp(APP_ID);
        userService = new UserService(this);
        vipService = new VipService(this);
        helper = new LoadViewHelper(whole_layout);
        helper.showLoading("正在加载。。。");

        adapter = new RecommendPresentAdapter(context, data);
        rvRecommendPresent.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        rvRecommendPresent.setAdapter(adapter);
        getNeedData();
//        getRankingData();
    }

    public void RequestData() {
        addDisposableIoMain(userService.getHighestReward(), new DefaultConsumer<List<RankingBean>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<RankingBean>> result) {
                data.addAll(result.getData());
                adapter.notifyDataSetChanged();
            }
        });
    }

    public void getNeedData() {
        addDisposableIoMain(userService.getSumUserIncome(), new DefaultConsumer<CommonResult>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<CommonResult> result) {
                invite_sum_reward_tv.setText("¥" + result.getData().getInvitationRewardsSum());
                charge_sum_reward_tv.setText("¥" + result.getData().getMembershipRewardsSum());
                partner_interest_tv.setText("¥" + result.getData().getDividendSum());
                getQRCode();
            }
        });
    }

    @OnClick({R.id.invite_sum_reward_ll, R.id.charge_sum_reward_ll, R.id.partner_interest_ll, R.id.share_btn})
    public void handleClickSth(View view) {
        switch (view.getId()) {
            case R.id.invite_sum_reward_ll:
                DialogController.showRecommendPresentDialog(RecommendPresentActivity.this, 9);
                break;
            case R.id.charge_sum_reward_ll:
                DialogController.showRecommendPresentDialog(RecommendPresentActivity.this, 10);
                break;
            case R.id.partner_interest_ll:
                DialogController.showRecommendPresentDialog(RecommendPresentActivity.this, 4);
                break;
            case R.id.share_btn:
                if (!CommonUtil.isFastClick()) {
                    shareToWinxin(qr_code_image_url);
                }
                break;
        }
    }

    public void getQRCode() {
        addDisposableIoMain(vipService.getQRCode(), new DefaultConsumer<CommonResult>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<CommonResult> result) {
                mApplication.getImageLoaderFactory().loadCommonImgByUrl(mActivity, result.getData().getQr_code(), qr_code_iv);
                qr_code_image_url = result.getData().getQr_code();
                desc_tv.setText(result.getData().getShowText());
                getUserCode();
            }
        });
    }

    /**
     * 获取用户生成推荐二维码所需要的参数
     */
    public void getUserCode() {
        addDisposableIoMain(userService.getUserCode(), new DefaultConsumer<CommonResult>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<CommonResult> result) {
                Bitmap mBitmap = CodeUtils.createImage(result.getData().getQRCode(), DensityUtil.dp2px(100), DensityUtil.dp2px(100), null);
                //qr_code_iv.setImageBitmap(mBitmap);
                helper.showContent();
            }
        });
    }

    public void initPopup() {
        easyPopup = EasyPopup.create(mActivity)
                .setContentView(getShareView())
                .setAnimationStyle(R.style.Popupwindow)
                .setBackgroundDimEnable(true)
                .setDimValue(0.4f)
                .setDimColor(Color.GRAY)
                .setDimView(whole_layout)
                .setFocusAndOutsideEnable(true)
                .setWidth(ViewGroup.LayoutParams.MATCH_PARENT)
                .setHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
                .apply();
    }

    public void showSharePopup() {
        easyPopup.showAtLocation(share_btn, Gravity.BOTTOM, 0, 0);
    }

    public View getShareView() {
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.layout_bottom_sheet_share, null);
        setButtonListeners(layout);
        return layout;
    }

    public void setButtonListeners(LinearLayout layout) {
        TextView wx_share_tv = layout.findViewById(R.id.wx_share_tv);
        TextView qq_share_tv = layout.findViewById(R.id.qq_share_tv);
        TextView cancelTv = layout.findViewById(R.id.cancel_tv);
        cancelTv.setOnClickListener((View v) -> {
            if (easyPopup != null && easyPopup.isShowing()) {
                easyPopup.dismiss();
            }
        });
        wx_share_tv.setOnClickListener((View view) -> {
            if (easyPopup != null && easyPopup.isShowing()) {
                easyPopup.dismiss();
            }
            //share(SHARE_TYPE.Type_WXSceneSession);
            //showToast("你点击了微信分享");
        });

        qq_share_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (easyPopup != null && easyPopup.isShowing()) {
                    easyPopup.dismiss();
                }
                //showToast("你点击了QQ分享");
            }
        });

    }

    private void share(SHARE_TYPE type, Bitmap bitmap) {
        //初始化WXImageObject和WXMediaMessage对象
        WXImageObject imageObject = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imageObject;
        //设置缩略图
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, DensityUtil.dp2px(40), DensityUtil.dp2px(40), true);
        bitmap.recycle();
        msg.thumbData = bmpToByteArray(thumbBmp, true);
        //构造一个请求
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");//transaction字段用于唯一标识一个请求
        req.message = msg;
        switch (type) {
            case Type_WXSceneSession:
                req.scene = WXSceneSession;
                break;
            case Type_WXSceneTimeline:
                req.scene = WXSceneTimeline;
                break;
        }
        iwxapi.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public void shareToWinxin(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;
                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    share(SHARE_TYPE.Type_WXSceneSession, bitmap);
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
